import { _decorator, Component, Node, UITransform, Vec3 } from 'cc';
import { Data } from './Data';
import {Game} from "./Game";
const { ccclass, property } = _decorator;

@ccclass('Backgrounds')
export class Backgrounds extends Component {
    /**
     * 前 中 后 -- 前/后 图片索引
     */
    private frontIndex!: number;
    private backIndex!: number;
    /**
     * 存储三张背景图的子节点数组
     */
    private bg: Node[] = new Array<Node>(3);
    /**
     * 对外初始化接口
     */
    public init(){
        this.setInitProperties();
        this.initIndex();
    }
    /**
     * 获取所有子节点到bg
     */
    private getChild() {
        for (let i = 0; i < this.bg.length; i++) {
            this.bg[i] = this.node.getChildByName('Bg_0' + (i + 1).toString())!;
        }
    }
    /**
     * 设置子节点初始属性
     */
    private setInitProperties(){
        for (let i = 0; i < this.bg.length; i++) {
            /**
             * 设置width height
             */
            this.bg[i].getComponent(UITransform)!.width = Data.Bg.width;
            this.bg[i].getComponent(UITransform)!.height = Data.Bg.height;
            /**
             * 设置初始位置
             */
            this.bg[i].setPosition(new Vec3(i * Data.Bg.width, 0));
        }
    }
    /**
     * 初始化前/后索引
     */
    private initIndex(){
        this.frontIndex = 0;
        this.backIndex = this.bg.length - 1;
    }
    /**
     * 更新前/后索引
     */
    private updateIndex(){
        this.frontIndex++;
        this.backIndex++;
        if (this.frontIndex == this.bg.length) {
            this.frontIndex = 0;
        }
        if (this.backIndex == this.bg.length) {
            this.backIndex = 0;
        }
    }
    /**
     * 向左移动
     */
    private leftMove(dt: number){
        for (let i = 0; i < this.bg.length; i++) {
            this.bg[i].setPosition(new Vec3(this.bg[i].position.x + Data.Bg.xSpeed * dt, 0));
        }
    }
    /**
     * 判断是否需要重置最前方图片的位置
     */
    private isNeedResetFrontPos() : boolean {
        return this.bg[this.frontIndex].position.x <= -Data.Bg.width;
    }
    /**
     * 重置 前 中 后 -- 前 图片位置
     */
    private resetFrontPos(){
        this.bg[this.frontIndex].setPosition(new Vec3(this.bg[this.backIndex].position.x + Data.Bg.width, 0));
        this.updateIndex();
    }
    /**
     * 子类实现
     */
    protected onLoad(){
        this.getChild();
    }

    protected start(){
        this.setInitProperties();
        this.initIndex();
    }

    protected update(dt: number){
        if (!Game.isPaused){
            this.leftMove(dt);
            if (this.isNeedResetFrontPos()) {
                this.resetFrontPos();
            }
        }
    }
}